package com.lxl.jwt1.service;

import com.lxl.jwt1.dao.UserMapper;
import com.lxl.jwt1.entity.TUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tuser = userMapper.findByUsername(username);//从数据库中查询用户
        if (tuser == null) {
            throw new UsernameNotFoundException("帐户不存在");
        }
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(tuser.getUsername()));//添加角色
        //下面的密码一般要加密
        return new User(tuser.getUsername(), new BCryptPasswordEncoder().encode(tuser.getPassword()), authorities);
    }
}
